package cn.wolfcode.luowowo.wensite.web.controller;

import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.member.util.AjaxResult;
import cn.wolfcode.luowowo.wensite.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;


@Controller
@ControllerAdvice
class LoginController {
    @Reference
    private IUserInfoService userInfoService;

    @RequestMapping("/hello")
    @ResponseBody
    public Object getIUserInfo(Long id) {
        return userInfoService.getUserInfo(id);
    }

    @RequestMapping("/checkPhone")
    @ResponseBody
    public Object checkPhone(String phone) {
        return !userInfoService.getPhone(phone);
    }

    @RequestMapping("/sendVerifyCode")
    @ResponseBody
    public Object sendVerifyCode(String phone) {
        userInfoService.sendVerifyCode(phone);
        return AjaxResult.SUCCESS;
    }

    @RequestMapping("/userRegist")
    @ResponseBody
    public Object userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        userInfoService.userRedis(phone, nickname, password, rpassword, verifyCode);
        return AjaxResult.SUCCESS;
    }

    @RequestMapping("/userLogin")
    @ResponseBody
    public Object userLogin(HttpServletResponse response, String username, String password) {
        String token = userInfoService.userLogin(username, password);
        /**
         * 将用户信息保存在cookie中,
         * 第一个参数:response,主要是将cookie带到浏览器中
         * 第二个参数:cookie是以键值对方式存数据的,所以我们存个key值,方便我们找到想要的cookie
         * 第三个参数:cookie中的实际信息,也就是用户缓存在redis中的信息
         * 第四个参数:表示用户缓存在redis中的数据有效时间
         */
        CookieUtil.addCookie(response, "token", token, RedisKeys.USER_LOGIN.getTime().intValue());
        return AjaxResult.SUCCESS;
    }
}